package com.huiyin.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.broadcast.YsfMessageReceiverActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.ImageLoaderListener;
import com.qiyukf.unicorn.api.ProductDetail;
import com.qiyukf.unicorn.api.SavePowerConfig;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.UnicornImageLoader;
import com.qiyukf.unicorn.api.UnreadCountChangeListener;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qiyukf.unicorn.api.YSFUserInfo;

/**
 * 七鱼云客服系统
 * 
 * @author zhyao
 * 
 */
public class YsfUtil {

	public static final String SECRET_KEY = "6f449658310741dc3b2b31b48e11f334";
	
	public static final String NAME = "汇银全球家客服";

	private static final String TAG = "YsfUtil";
	
	public static String ysfAppId() {
		return SECRET_KEY;
	}

	public static String staffName() {
        return NAME;
    }
	 
	public static void init(Context context) {

		boolean flag = Unicorn.init(context, YsfUtil.ysfAppId(), YsfUtil.ysfOptions(), new YsfUtil().new UILImageLoader());
		if (flag) {
            Log.d(TAG, "init qiyu sdk success!");
        }
		else {
			Log.w(TAG, "init qiyu sdk error!");
		}
	}
	
	public static YSFOptions ysfOptions() {
		YSFOptions options = new YSFOptions();
		StatusBarNotificationConfig config = new StatusBarNotificationConfig();
		config.notificationEntrance = YsfMessageReceiverActivity.class;
		options.statusBarNotificationConfig = config;
		options.statusBarNotificationConfig.notificationSmallIconId = R.drawable.ic_launcher;
		options.savePowerConfig = new SavePowerConfig();
		return options;
	}
	
	public static void setYsfUserInfo(String userId, String userName, String phone) {
		Log.d(TAG, "setYsfUserInfo : userId = " + userId + " userName = " + userName + " phone = " + phone);
		YSFUserInfo userInfo = new YSFUserInfo();
		userInfo.userId = userId;
		userInfo.data="[{\"key\":\"real_name\", \"value\":\"" + userName + "\"},"
		             + "{\"key\":\"mobile_phone\",\"value\":\"" + phone + "\",\"hidden\":" + false + "}]";
		Unicorn.setUserInfo(userInfo);
		
		Log.d(TAG, "YsfUserInfo = " + userInfo.data);

	}

	public static void clearYsfUserInfo() {
		Log.d(TAG, "clearYsfUserInfo");
		Unicorn.setUserInfo(null);
	}

	
	/**
	 * 生成商品信息
	 * @param title	商品标题	长度限制为 100 字符，超过自动截断。
	 * @param desc	商品详细描述信息。	长度限制为 300 字符，超过自动截断。
	 * @param note	商品备注信息（价格，套餐等）	长度限制为 100 字符，超过自动截断。
	 * @param picture	缩略图图片的 url。	该 url 需要没有跨域访问限制，否则在客服端会无法显示。
	 * @param 长度限制为 1000 字符， 超长不会自动截断，但会发送失败。
	 * @param url	商品信息详情页 url。	长度限制为 1000 字符，超长不会自动截断，但会发送失败。
	 * @param show	是否在访客端显示商品消息。	默认为false，即客服能看到此消息，但访客看不到，也不知道该消息已发送给客服。
	 * @return
	 */
	public static ProductDetail generateProductDetail(String title, String desc, String note, String picture, String url, int show) {
		return new ProductDetail
				.Builder()
				.setTitle(title)
				.setDesc(desc)
				.setNote(note)
				.setPicture(picture)
				.setUrl(url)
				.setShow(show)
				.create();
	}
    
    public static void consultService(final Context context, String uri, String title, ProductDetail productDetail) {
        if (!Unicorn.isServiceAvailable()) {
            UIHelper.showToast("客服系统异常");
            return;
        }
        
        setYsfUserInfo(AppContext.mUserInfo.userId, AppContext.mUserInfo.userName, AppContext.mUserInfo.phone);

        // 启动聊天界面
        ConsultSource source = new ConsultSource(uri, title, null);
        source.productDetail = productDetail;
        Unicorn.openServiceActivity(context, staffName(), source);
    }
    
    public static int getUnreadCount() {
    	return Unicorn.getUnreadCount();
    }
    
    public static void addUnreadCountChangeListener(UnreadCountChangeListener listener, boolean add) {
        Unicorn.addUnreadCountChangeListener(listener, add);
    }
    
    public class UILImageLoader implements UnicornImageLoader {
        private static final String TAG = "UILImageLoader";

        @Override
        public Bitmap loadImageSync(String uri, int width, int height) {
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)
                    .cacheOnDisk(false)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .build();

            // check cache
            boolean cached = MemoryCacheUtils.findCachedBitmapsForImageUri(uri, ImageLoader.getInstance().getMemoryCache()).size() > 0
                    || DiskCacheUtils.findInCache(uri, ImageLoader.getInstance().getDiskCache()) != null;
            if (cached) {
                Bitmap bitmap = ImageLoader.getInstance().loadImageSync(uri, new ImageSize(width, height), options);
                if (bitmap == null) {
                    Log.e(TAG, "load cached image failed, uri =" + uri);
                }
                return bitmap;
            }
        	
        	

            return null;
        }

        @Override
        public void loadImage(String uri, int width, int height, final ImageLoaderListener listener) {
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)
                    .cacheOnDisk(false)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .build();

            ImageLoader.getInstance().loadImage(uri, new ImageSize(width, height), options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    super.onLoadingComplete(imageUri, view, loadedImage);
                    if (listener != null) {
                        listener.onLoadComplete(loadedImage);
                    }
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    super.onLoadingFailed(imageUri, view, failReason);
                    if (listener != null) {
                        listener.onLoadFailed(failReason.getCause());
                    }
                }
            });
        }
    }

    public static boolean inMainProcess(Context context) {
		String packageName = context.getPackageName();
		String processName = getProcessName(context);
		return packageName.equals(processName);
	}
	
	 /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    public static final String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            }

            // go home
            if (!StringUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
